import axios from "axios";
import {Message} from "@arco-design/web-vue";
import {deleteStorage, getStorage, USER_TOKEN} from "@/utils/localStorage";
// 注册响应拦截器
axios.interceptors.response.use(
    res => {
        if (res.status === 200) {
            switch (res.data.code) {
                case 200:
                    return res.data;
                case 401:
                    Message.error('登录认证已过期，请重新登录');
                    setTimeout(() => {
                        // token过期 删除localStorage
                        deleteStorage(USER_TOKEN);
                        // 将路由导航到根路径
                        location.href = location.origin
                    }, 1000)
                    break
                default :
                    Message.error(res.data.message)
            }
        } else {
            throw res.status;
        }
    },
    error => {
        // 处理网络错误等异常情况
        throw error;
    }
);

const requestWhiteList = ["/api/user/login", '/api/github/clientId', '/api/github/getToken'];
axios.interceptors.request.use((config) => {
    const requestUrl = config.url;
    if (!requestUrl) {
        return config;
    }

    const pathName = requestUrl.indexOf('?') !== -1 ? requestUrl.slice(0, (requestUrl.indexOf('?') + 1)) : requestUrl
    // 在每次请求之前 需要在请求头带上token
    const token = getStorage(USER_TOKEN);
    if (token) {
        config.headers.Authorization = `Bearer ${token}`;
    }
    if (!token && !requestWhiteList.includes(pathName)) {
        Message.error('登录认证已过期，请重新登录');
        // 如果没有token 并且 当前请求的url不在白名单中 那就说明当前用户没有认证
        location.href = location.origin;
        return new Promise(() => {
            throw new Error('token丢失')
        })
    }
    return config
})

export default axios;
